package org.gikolet.ch2.android.dao;

import org.gikolet.ch2.android.dao.Schema.Boards;
import org.gikolet.ch2.android.dao.Schema.ThreadHeaders;

import roboguice.inject.ContextScoped;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.google.inject.Inject;

@ContextScoped
public class SQLiteHelper extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "gikolet.db";
	private static final int DATABASE_VERSION = 1;

	private static final String SQL_CREATE_TABLE_BOARDS = "CREATE TABLE "
			+ Boards.TBL_NAME + "(" + Boards.Columns.ID.column()
			+ " INTEGER PRIMARY KEY" + "," + Boards.Columns.HOST_NAME.column()
			+ " VARCHAR NOT NULL" + "," + Boards.Columns.PATH.column()
			+ " VARCHAR NOT NULL" + "," + Boards.Columns.NAME.column()
			+ " VARCHAR NOT NULL" + ",UNIQUE("
			+ Boards.Columns.HOST_NAME.column() + "," + Boards.Columns.PATH
			+ ")" + ");";

	private static final String SQL_CREATE_TABLE_THREAD_HEADERS = "CREATE TABLE "
			+ ThreadHeaders.TBL_NAME
			+ "("
			+ ThreadHeaders.Columns.ID.column()
			+ " INTEGER PRIMARY KEY"
			+ ","
			+ ThreadHeaders.Columns.BOARD_ID.column()
			+ " VARCHAR NOT NULL"
			+ ","
			+ ThreadHeaders.Columns.THREAD_KEY.column()
			+ " VARCHAR NOT NULL"
			+ ","
			+ ThreadHeaders.Columns.SUBJECT.column()
			+ " VARCHAR NOT NULL"
			+ ","
			+ ThreadHeaders.Columns.RES_COUNT.column()
			+ " VARCHAR NOT NULL"
			+ ","
			+ ThreadHeaders.Columns.DATE.column()
			+ " VARCHAR NOT NULL"
			+ ","
			+ ThreadHeaders.Columns.LAST_MODIFIED.column()
			+ " VARCHAR NOT NULL"
			+ ","
			+ ThreadHeaders.Columns.BYTE_SIZE.column()
			+ " VARCHAR NOT NULL"
			+ ",UNIQUE("
			+ ThreadHeaders.Columns.BOARD_ID.column()
			+ ","
			+ ThreadHeaders.Columns.THREAD_KEY + ")" + ");";

	@Inject
	public SQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_TABLE_BOARDS);
		db.execSQL(SQL_CREATE_TABLE_THREAD_HEADERS);
	}

	// DBバージョンが上がった場合の動作
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// 削除してまた作成
		db.execSQL("DROP TABLE IF EXISTS " + Boards.TBL_NAME);
		db.execSQL("DROP TABLE IF EXISTS " + ThreadHeaders.TBL_NAME);

		onCreate(db);
	}
}
